package com.mt.component.scanner;

import java.io.File;

import com.mt.component.annotation.Manager;

public class BeanScanner {
	
	private ClassLoader classLoader;
	
	private String basePath = "E:\\360云盘\\workspace\\javaee\\MSHF\\WebRoot\\WEB-INF\\classes";
	
	public void scanner(String[] packages){
		classLoader = Thread.currentThread().getContextClassLoader();
		for (String pk : packages) {
			handle(basePath + File.separator + packageToDir(pk));
		}
	}
	
	private void handle(String scannerPath) {
		File file = new File(scannerPath);
		if (file.isDirectory()) {
			handleDirectory(file);
		}
	}

	private void handleDirectory(File file) {
		for (File child : file.listFiles()) {
			if (child.isDirectory()) {
				handleDirectory(child);
			} else {
				if (child.getName().endsWith(".class")) {
					String filename = filenameToClassname(child.getAbsolutePath());
					try {
						Class clazz = classLoader.loadClass(filename);
						if(clazz.isAnnotation()){
							if (clazz.isAnnotationPresent(Manager.class)) {
								Manager manager = (Manager)clazz.getAnnotation(Manager.class);
							}
						}else if(clazz.isInterface()){
							
						}else if(clazz.isEnum()){
							
						}else{
							Object object = clazz.newInstance();
							System.out.println(object);
						}
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	protected String filenameToClassname(String filename) {
		filename = filename.substring(basePath.length() + 1);
		return filename.substring(0, filename.lastIndexOf(".class")).replace('/', '.').replace('\\', '.');
	}

	private String packageToDir(String pack){
		return pack.replace(".", File.separator);
	}
	
	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}

	public static void main(String[] args) {
		String[] packages = new String[]{
			"com.mt"
		};
		new BeanScanner().scanner(packages);
	}
}
